import pandas as pd
import os

uncertainty = 0.01

def fmt(x):
    return rf"${x:.2f} \pm {uncertainty:.2f}$"


files_vext195 = [
    ("0.92", "vext195vret092.csv"),
    ("1.92", "vext195vret192.csv"),
    ("2.91", "vext195vret291.csv"),
]

files_vret150 = [
    ("1.50", "vret150vext150.csv"),
    ("2.50", "vret150vext250.csv"),
]

def make_table(title, fixed_label, blocks):
    n = len(blocks)
    cols = "cc|" * (n - 1) + "cc"

    latex = []

    latex.append(rf"\begin{{longtable}}{{{cols}}}")
    latex.append(rf"\caption{{Datos medidos en laboratorio}} \\")
    latex.append(r"\toprule")

    latex.append(rf"\multicolumn{{{2*n}}}{{c}}{{ {title} }} \\")
    latex.append(r"\midrule")

    # headers
    header = []
    for val, _ in blocks:
        header.append(rf"\multicolumn{{2}}{{c}}{{ {fixed_label} = {val} \pm 0.01 \quad V }}")

    latex.append(" & ".join(header) + r" \\")
    latex.append(r"\midrule")

    latex.append(" & ".join([r"$V_{ac}$ (V) & $V_a$ (V)"] * n) + r" \\")
    latex.append(r"\midrule")
    latex.append(r"\endfirsthead")

    latex.append(r"\midrule")
    latex.append(" & ".join([r"$V_{ac}$ (V) & $V_a$ (V)"] * n) + r" \\")
    latex.append(r"\midrule")
    latex.append(r"\endhead")

    latex.append(r"\bottomrule")
    latex.append(r"\endfoot")

    dfs = []
    for _, file in blocks:
        dfs.append(pd.read_csv(file))

    max_len = max(len(df) for df in dfs)

    for i in range(max_len):
        row = []
        for df in dfs:
            if i < len(df):
                row.append(f"{fmt(df.iloc[i,0])} & {fmt(df.iloc[i,1])}")
            else:
                row.append(" & ")
        latex.append(" & ".join(row) + r" \\")

    latex.append(r"\end{longtable}")
    return "\n".join(latex)

out = []

out.append(make_table(
    "$V_{ext} = 1.95\pm 0.01$ V",
    "V_{ret}",
    files_vext195
))

out.append(make_table(
    "$V_{ret} = 1.50\pm 0.01$ V",
    "V_{ext}",
    files_vret150
))

with open("tablas_generadas.tex", "w") as f:
    f.write("\n\n".join(out))

print("---> Tablas generadas correctamente <---")